const wxaapi = require('../../public/wxaapi.js');//api地址参数
const wxRequest = require('../../utils/js/wxRequest.js'); //请求参数
const event = require('../../public/js/wxEvent.js'); //事件上报相关参数
Page({
  data: {
    oUserInfo:{},//当前用户
    isShowMask: false, //是否显示领取成功
    lotteryNum:0,//抽奖次数
    rules:"",//活动规则
    desUrl:"",//活动说明图片
    totalCount:0,//总量
    aAwardsData:{},//当前大转盘对象
    aRecoders: [], //中奖记录
    aAwardsList: [], //奖品列表
    isChance: false, //
    rotateDegs: 0, //旋转角度
    aAwardsItems: [], //列表显示
    animationData: {},
    isDisabled: '', //按钮是否可用
    clinicId:'',
    oClinic:{},//诊所信息
    cstUid:"",//咨询师
    oSelectPrize:{},//选中的奖品
    oEvent: {},
    leftNum:0,//剩余次数
    iTick:0,//计时器
  },
  onLoad:function(options){
    console.log("options===========",options)
    let _This=this;
    let {sessionId,clinicId,wheelId} = options;
    clinicId = clinicId || wx.getStorageSync("clinicId") || "";
    if (clinicId) {
      wx.setStorageSync("clinicId", clinicId);
    }
    getApp().getUserData(function (oUinfo) {
       _This.setData({
         oUserInfo:oUinfo||{},
         sessionId: sessionId || "3218",//3218
         clinicId: clinicId||"3",//3
         wheelId: wheelId||"15"//15
       });
      _This.fGetBigWheel();
      _This.fGetClinicDetailByClinicId();

      //获取分享人信息
      _This.fGetShareInfoBySessionId().then(cstInfo=>{
        _This.setData({
          cstUid: cstInfo.unionId,
          userId: cstInfo.userId
        });
        _This.fCustomerAdd();//添加用户获取线索
        wx.setStorageSync('userId', cstInfo.userId);
        wx.setStorageSync("cst_unionid", cstInfo.unionId);//设置网络咨询师unionid用户首页跳转
     // _This.fUserEvent(event.eType.openWheel);//打开大转盘
      });
wx.showShareMenu({
  
})

    });
  },
  /**
   * 获取诊所大转盘信息
   */
  fGetBigWheel:function(){
    let _This = this;
    let pdata = {
      clinicId:_This.data.clinicId,
      customerUnId: _This.data.oUserInfo.unionId
    };
      wx.showLoading({
        title: 'loading...',
      });
      let oData={};
    wxRequest(wxaapi.bigwheel.getwheel.url, pdata).then(function (result) {
       console.log("fGetBigWheel---- result---------------", result, pdata);
      if (result.data.code == 0 && result.data.data!="null"){
        oData=result.data.data;
        //console.log("oData.bigWheelGoodsList----22222-----------", result.data);
       _This.setData({
         aAwardsData:oData,
         wheelId: oData.id,
         aAwardsList: oData.bigWheelGoodsList,
         lotteryNum: oData.lotteryNum,
         rules: oData.rules,
         leftNum: oData.leftNum>0?oData.leftNum:0,
         desUrl: oData.file.url
       });
        _This.fCalculateAwards();
        return oData.id;
      }else{
        return 0;
      }
    }).then(wheelId=>{
      wx.hideLoading();
      if (oData.isOpen!=1) {
        wx.reLaunch({
          url: '/pages/index',
        })
      }
      _This.fGetRecoders(1);
    });
  },
  /**
   * 获取中奖记录信息
   */
  fGetRecoders(isFirst){
    let _This=this;
    let { clinicId, wheelId, iTick}=_This.data;
   // clearInterval(iTick);
    let oWheelData = {
      customerUnId: "",
      wheelId: wheelId,
      clinicId:clinicId,
      pageNo: 1,
      pageSize: 100,
    }
    wxRequest(wxaapi.selltool.bigWheelGoodsPageList.url, oWheelData).then(function (result) {
      if (result.data.code == 0) {
        let oDataList = result.data.data.list || [];
        oDataList.forEach((item, index) => {
          item.index = index;
        });
        _This.setData({
          aRecoders: oDataList
        });
        if (isFirst){
          let iTick= setInterval(() => {
            let aRecoders = _This.data.aRecoders;
            aRecoders.forEach((item) => {
              let index = --item.index;
              if (index <-1) {
                index = aRecoders.length-2;
              }
              item.index = index;
            });
            _This.setData({
              aRecoders: aRecoders,
              iTick: iTick
            });
          }, 2000);

        }
      }
    })
  },
  /**
   * 中奖奖品信息计算
   */
  fCalculateAwards:function(){
    let _This = this;
    let aAwardsList = _This.data.aAwardsList||[];
    let iAwardsLength = aAwardsList.length || 1,
      aAwardsItems = [],
      turnNum = 1 / iAwardsLength;
    let totalCount=0;
    let currentTime=new Date().getTime();
    aAwardsList.forEach((oItem,index)=>{
      let iPrizeRate=0;
      let expireDate =oItem.codeExpireDate+60000*60*24;
      if (oItem.stockNum > 0 && currentTime<=expireDate){
        iPrizeRate = oItem.prizeRate;
      }
      totalCount += iPrizeRate;
      aAwardsItems.push({
        turn: index * turnNum + 'turn',
        lineTurn: index * turnNum + turnNum / 2 + 'turn',
        award: oItem.name,
        prizeRate: iPrizeRate
      });
    });
    _This.setData({
      aAwardsItems: aAwardsItems,
      totalCount: totalCount
    });
  },
  /**
   * 点击抽奖进行奖品中奖率重新计算（重新获取奖品信息进行计算）
   */
 fReclickDraw:function(){
   let _This = this;
   let { clinicId, oUserInfo}=_This.data;
   let pdata = {
     clinicId:clinicId,
     customerUnId:oUserInfo.unionId
   };
   let oData = {};
   wxRequest(wxaapi.bigwheel.getwheel.url, pdata).then(function (result) {
     if (result.data.code == 0 && result.data.data != "null") {
       oData = result.data.data;
       _This.setData({
         aAwardsList: oData.bigWheelGoodsList,
         lotteryNum: oData.lotteryNum,
         leftNum: oData.leftNum > 0 ? oData.leftNum : 0,
       });
       if (oData.isOpen != 1) {
         wx.showToast({
           title: '活动已结束',
           icon: 'none',
           duration: 2000
         })
         return false;
       }
       _This.fReCalculateAwards();
     } 
   })
 },
  /**
   * 重新计算中奖奖品信息
   */
  fReCalculateAwards: function () {
    let _This = this;
    let aAwardsList = _This.data.aAwardsList || [];
    let totalCount = 0;
    let currentTime = new Date().getTime();
    aAwardsList.forEach((oItem, index) => {
      let iPrizeRate = 0;
      let expireDate = oItem.codeExpireDate + 60000 * 60 * 24;
      if (oItem.stockNum > 0 && currentTime <= expireDate) {
        iPrizeRate = oItem.prizeRate;
      }
      totalCount += iPrizeRate;
      oItem.prizeRate = iPrizeRate;
    });
    _This.setData({
      totalCount: totalCount,
      aAwardsList: aAwardsList
    });
    _This.fLuckdraw(); //重新计算领取礼品 
  },
  /**
   * 点击抽奖
   */
  fLuckdraw: function() {
    let _This = this;
    _This.fUserEvent(event.eType.luckDraw);//进入点击抽奖
    let {
      rotateDegs,
      aAwardsList,
      isChance,
      totalCount,
      aAwardsItems,
      leftNum
    } = _This.data;
    if (leftNum<=0){
      wx.showToast({
        title: '剩余次数0',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    let iAwardsLength = aAwardsList.length || 1;
    let iAwardIndex = Math.random() * iAwardsLength >>> 0;
    if (totalCount<=0){
      wx.showToast({
        title: '活动已结束',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (_This.data.isDisabled){
      return false;
    }
    let currentSelectData = Math.random()*totalCount;
    if (currentSelectData==0){
      currentSelectData = Math.random()*totalCount;
    }
    // console.log("totalnum------------", totalCount, currentSelectData, iAwardIndex);
    let isSelect=false;
    let itemAccount=0;
    aAwardsList.forEach((oItem, index) => {
      itemAccount+=oItem.prizeRate;
      if (itemAccount >= currentSelectData &&!isSelect){
        isSelect=true;
        iAwardIndex = index;
      }
    });
    let runNum = 8;
    rotateDegs = rotateDegs + (360 - rotateDegs % 360) + (360 * runNum - iAwardIndex * (360 / iAwardsLength));
    //console.log('deg----2222222-------', rotateDegs);
    let oLuckWheel = wx.createAnimation({
      duration: 4000,
      timingFunction: 'ease'
    });
    _This.oLuckWheel = oLuckWheel;
    oLuckWheel.rotate(rotateDegs).step();
    _This.setData({
      animationData: oLuckWheel.export(),
      isDisabled: 'disabled',
      rotateDegs: rotateDegs,
      oSelectPrize: aAwardsList[iAwardIndex] //选中的奖项
    });

    // 中奖提示
    setTimeout(function() {
    //  console.log('aAwardsList[iAwardIndex]-----2222222-------', aAwardsList[iAwardIndex]);
      _This.fCreateBigWheel();//抽中奖品
    }, 4000);
  },
  onReady: function(e) {

  },
  /**
   * 领取奖品
   */
  fCreateBigWheel(){
    let _This = this;
    let { oSelectPrize, sessionId, userId, cstUid, clueId, oUserInfo, clinicId, wheelId,leftNum}=_This.data;
    let pdata = {
      "bizId": oSelectPrize.id,
      "sessionId": sessionId,
      "consultId": userId,
      "consultUnId": cstUid,
      "clueId": clueId,
      "customerName": oUserInfo.nickName,
      "bizName": oSelectPrize.name,
      "wechatMobile": oUserInfo.wechatMobile||"",
      "clinicId": clinicId,
      "customerUnId": oUserInfo.unionId,
      "customerLogo": oUserInfo.avatarUrl,
      "customerId": oUserInfo.id,
      "bizType": "",
      "wheelId": wheelId,
      "tenantId": ""
    }
    wxRequest(wxaapi.selltool.createbigwheel.url, pdata).then(function (result) {
     // console.log("fCreateBigWheel---------------", result, pdata);
      if (result.data.code == 0) {
        _This.fUserEvent(event.eType.winningThePrize);//抽中奖品
        _This.fGetRecoders();
        _This.setData({ //弹出抽奖成功
          leftNum: --leftNum,
          isDisabled: '',
          isShowMask: true
        });
      }else{
        //console.log("领取失败------------------", result);
        _This.setData({ 
          isDisabled: '',
        });
        wx.showToast({
          title: '活动已结束',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },
  /**
   * 关闭领取奖品成功
   */
  fCloseMask() {
    let _This = this;
    _This.setData({
      isShowMask: false
    })
  },
  /**
   * 导航到我的奖品
   */
  fNavToMyaward(){
    let _This = this;
    let { oClinic, aAwardsData, oUserInfo} = _This.data;
    _This.fUserEvent(event.eType.lookAtThePrize);//
    wx.navigateTo({
      url: `/pages/award/award?clinicId=${aAwardsData.clinicId}&wheelId=${aAwardsData.id}&customerUnId=${oUserInfo.unionId}`,
    })
    _This.setData({
      isShowMask: false
    })
  },
  /**
   * 导航到奖品说明
   */
  fNavToDes(){
    let _This = this;
    let desUrl = _This.data.desUrl;
    wx.navigateTo({
      url: `/pages/bigwheel/prizedes/prizedes?desUrl=${desUrl}`,
    })
  },
  /**
   * 获取诊所信息
   */
  fGetClinicDetailByClinicId(){
    let _This = this;
    let pdata = {
      clinicId: _This.data.clinicId
    };

    wxRequest(wxaapi.clinic.getdetailbyid.url, pdata).then(function (result) {
      //console.log("clinicInfo---------------", result, pdata);
      if (result.data.code == 0) {
        let oClinic = result.data.data;
        _This.setData({
          oClinic: oClinic
        });
      }
    });
  },
  fPick(){
    let _This = this;
    let oClinic = _This.data.oClinic;
    _This.fUserEvent(event.eType.receivePrize);//去领取
    wx.openLocation({
      latitude: Number(oClinic.coordinate.split(",")[1]) - 0.00634,
      longitude: Number(oClinic.coordinate.split(",")[0]) - 0.00647,
      name: oClinic.address,
      address: "联系电话："+oClinic.phone
    })
  },

///////////////////////////////1111111111111//////////////////////////////////////
  /**
   * 获取分享人信息
   */
  fGetShareInfoBySessionId() {
    let _This = this;
    let pdata = {
      sessionId: _This.data.sessionId
    };
    return wxRequest(wxaapi.consult.getconsultinfo.url, pdata).then(function (result) {
      if (result.data.code == 0) {
        return result.data.data;
      } else {
       // console.log("get unionid by sessionid error----", result, _This.data.sessionId);
        return {};
      }
    });
  },

///////////////////////////////1111111111111//////////////////////////////////////


  /**
   * 客户添加或者更新,返回线索id
   */
  fCustomerAdd(isNew) {
    let _This = this;
    let { oUserInfo, sessionId, userId, cstUid}=_This.data;
    let pdata = {
      wxaOpenid:oUserInfo.openId,
      openid:oUserInfo.openId,
      wxNickname:oUserInfo.nickName,
      gender:oUserInfo.gender,
      province:oUserInfo.province,
      city:oUserInfo.city,
      country:oUserInfo.country,
      logo:oUserInfo.avatarUrl,
      unionid:oUserInfo.unionId,
      userUnionid:cstUid,
      userId: userId,
      consultationId: sessionId
    };
    wxRequest(wxaapi.consult.entry.url, pdata).then(function (result) {
     // console.log("---fCustomerAdd---pdata---------->", pdata,result);
      if (result.data.code == 0) {
        _This.setData({
          clueId: result.data.data.clueId
        });
        wx.setStorageSync("clueId", result.data.data.clueId)
        _This.fUserEvent(event.eType.openWheel);//打开大转盘
        _This.fGetCustomerByUnionid(isNew);
      } else {
        console.log("addcustomer error----", result);
      }
    });
  },
  /**
   * 通过咨询师unionid和客户unionid获取客户信息
   */
  fGetCustomerByUnionid(isNew) {
    let _This = this;
    let { oUserInfo, cstUid} = _This.data;
    let pdata = {
      consultantUnionid:cstUid,
      unionid:oUserInfo.unionId
    };
    wxRequest(wxaapi.customer.getcustomerbyunid.url, pdata).then(function (result) {
      //console.log("get customer info result---->", result);
      if (result.data.code == 0) {
        oUserInfo.wechatMobile = result.data.data.wechatMobile;
        oUserInfo.id = result.data.data.id;
        _This.setData({
          oUserInfo: oUserInfo
        });
        if (isNew){//领取礼品，如果新授权，重新领取
          //_This.fLuckdraw(); 
          _This.fReclickDraw();
        }
      } else {
        console.log("get customer info error----", result);
      }
    });
  },
  /**
* 用户事件
*/
  fUserEvent(eType) {
    let _This = this;
    _This.fGetTempEvent();
    var oData = _This.data.oEvent;
    oData.eventAttrs.triggeredTime = new Date().valueOf();
    oData.code = eType;
    wxRequest(wxaapi.event.v2.url, oData).then(function (result) {
     // console.log("活动上报---*@@@@@@@@@@**------", oData, result);
      if (result.data.code == 0) {

      } else {
        console.log("add  event error---", result);
      }
    });
  },
  /*
   *事件参数 
   */
  fGetTempEvent() {
    let _This = this;
    let { oEvent, clueId, sessionId, cstUid, oUserInfo, wheelId, oSelectPrize} = _This.data;
    oEvent.shareEventId = 1;
    oEvent.productCode = [""];
    oEvent.clueId = clueId; //线索id  
    oEvent.leadsId = clueId; //线索id新  leadsId
    oEvent.consultationId = sessionId;//咨询会话ID
    oEvent.sceneId = sessionId;// 场景sceneId  oUserInfo.
    oEvent.eventAttrs = {
      wheelId: wheelId,
      doctorId: "",//医生id
      activityId: "",//活动id
      bizId: oSelectPrize.id||"",
      consultantId: cstUid,
      userId: _This.data.userId,
      clueId: clueId, //线索id  
      leadsId: clueId, //线索id新  leadsId
      consultationId: sessionId,//咨询会话ID
      sceneId: sessionId,// 场景sceneId  oUserInfo.
      caseId: "",//
      appletId: "hldn",
      consultingId: sessionId,
      isLike: 0,    ////0不喜欢 1喜欢2未选择
      reserveId: "",//
      agree: 1,  //1是允许，0是拒绝
      imgNum: "",
      imgUrls: [],
      remark: '',
      triggeredTime: new Date().getTime()
    }
    oEvent.subjectAttrs = {
      appid: "yxgj",
      consultantId: cstUid,
      openid: oUserInfo.openId || oUserInfo.openid,
      unionid: oUserInfo.unionId || oUserInfo.unionid,
      mobile: oUserInfo.wechatMobile || ""
    };
    //console.log('活动上报----@@@@@**', oEvent)
    _This.setData({
      oEvent: oEvent
    });
  },
  /**
* 客服用户授权
*/
  fContactUserAuthHandle(e) {
    let _This = this;
    let errMsg = e.detail.errMsg;
    if (errMsg.indexOf("ok") < 0) {
      wx.showToast({
        title: '请授权操作',
      });
      return false;
    }
    let { oUserInfo } = _This.data;
    if (oUserInfo.nickName) {
      //_This.fLuckdraw(); //已经授权用户直接领取
      _This.fReclickDraw();//已经授权用户直接领取
      return false;
    }
    getApp().fGetSessionKey(false, function (sessionKey) {
      var postData = {
        encryptedData: e.detail.encryptedData,
        sessionKey: sessionKey,
        iv: e.detail.iv
      };
      wxRequest(wxaapi.unionid.userinfo.url, postData).then(result => {
        //console.log("result user info---------------", result);
        let UInfo = _This.data.oUserInfo;
        if (result.errMsg.indexOf("ok") > 0) {
          UInfo = result.data.userinfo;
          _This.setData({
            oUserInfo:UInfo
          });
         _This.fCustomerAdd("1");
        }

      });
    });
  },
  /**
* 授权获取手机号码
*/
  getPhoneNumber(e) {
    let _This = this;
    wx.showLoading({
      title: '授权中...',
    });
    let eDetail = e.detail;
    if (!eDetail.encryptedData) {
      wx.hideLoading();
      return false;
    }
    getApp().fGetSessionKey(false, function (sessionKey) {
      let postData = {
        encryptedData: e.detail.encryptedData,
        sessionKey: sessionKey,
        iv: e.detail.iv
      };
      wxRequest(wxaapi.unionid.userinfo.url, postData).then(result => {
        let oUserInfo = _This.data.oUserInfo;
        if (result.errMsg.indexOf("ok") > 0) {
          oUserInfo.wechatMobile = result.data.userinfo.phoneNumber;
          _This.setData({
            oUserInfo: oUserInfo
          });
        _This.fUpdateCustomerInfo();
        }
        wx.hideLoading();
      });
    });
  },
  /**
 * 授权后更新客户手机号码
 */
  fUpdateCustomerInfo() {
    let _This = this;
    let oUserInfo = _This.data.oUserInfo;
    let pdata = {
      id: _This.data.oUserInfo.id,
      wechatMobile: _This.data.oUserInfo.wechatMobile
    };
    wxRequest(wxaapi.customer.update.url, pdata).then(function (result) {
      if (result.data.code == 0) {
        _This.fPick();//授权后导航的诊所信息
      } else {
        console.log("update customer info error----", result);
      }
    });
  },

})